<template>
  <div class="father">
    <h3>父组件</h3>
    <h4>房产：{{ house }}</h4>
    <button @click="changeC1Instr">修改孩子1的乐器</button>
    <button @click="changeC2Book">修改孩子2的书籍</button>
    <!-- $refs 拿子组件的数据，$parent 拿父组件的数据-->
    <button @click="getAll($refs)">获取所有的子组件实例对象</button>
    <Child1 ref="c1"></Child1>
    <Child2 ref="c2"></Child2>
  </div>
</template>

<script setup lang="ts" name="Father">
import Child1 from "./Child1.vue";
import Child2 from "./Child2.vue";
import { ref, watch } from "vue";

let house = ref(4);
let c1 = ref();
let c2 = ref();

function changeC1Instr() {
  console.log(c1.value);
  //在检查中无法看到，需要孩子1暴露数据
  c1.value.instrument = "尤克里里";
}

function changeC2Book() {
  c2.value.book = "乌合之众";
}

function getAll(x: any) {
  //console.log("c1", x.c1.instrument, "c2", x.c2.book);
  //可以将同一属性名进行循环然后变更（适用于多个对象）
  for (let key in x) {
    // console.log(key);  //获取得到c1, c2
    console.log(x[key]);
    x[key].collections += 3;
  }
}

defineExpose({ house });

watch(house, (newValue) => {
  if (newValue < 0) {
    return (house.value = 0);
  }
});
</script>

<style scoped>
.father {
  background-color: rgb(165, 164, 164);
  padding: 20px;
  border-radius: 10px;
}

.father button {
  margin-bottom: 10px;
  margin-left: 10px;
}
</style>

